<?php

namespace app\modules\controllers;
use app\models\Category;
use app\models\Product;
use yii\web\Controller;
use Yii;
use yii\data\Pagination;
use crazyfd\qiniu\Qiniu;
use app\modules\controllers\CommonController;
use yii\web\UploadedFile;

class ProductController extends CommonController
{
    public function actionList()
    {
        $model = Product::find();
        $count = $model->count();
        $pageSize = Yii::$app->params['pageSize']['product'];
        $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]);
        $products = $model->offset($pager->offset)->limit($pager->limit)->all();
        $this->layout = "layout1";
        return $this->render("products", ['pager' => $pager, 'products' => $products]);
    }

    public function actionAdd()
    {
        $this->layout = "layout1";
        $model = new Product;

        //设置"热卖、促销、上架、推荐"默认值
        $model->ishot = 0;
        $model->issale = 0;
        $model->ison = 1;
        $model->istui = 0;

        //类别下拉选单
        $cate = new Category;
        $list = $cate->getOptions();
        unset($list[0]);
        
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();

            //上传封面图片和多张商品图片
            $uploadImgUrl = $this->upload($model, 'add');
            $post['Product']['cover'] = $uploadImgUrl['cover'];
            $post['Product']['pics'] = $uploadImgUrl['pics'];

            //定义必要的属性值满足数据库字段类型限制
            $post['Product']['saleprice'] = ($post['Product']['saleprice'] != '') ? $post['Product']['saleprice'] : 0.00;
            $post['Product']['num'] = ($post['Product']['num'] != '') ? $post['Product']['num'] : 0;

            if ($model->add($post))
            {
                Yii::$app->session->setFlash('info', '添加成功');
            }
        }

        return $this->render("add", ['opts' => $list, 'model' => $model]);
    }

    public function actionMod()
    {
        $this->layout = "layout1";
        $cate = new Category;
        $list = $cate->getOptions();
        unset($list[0]);

        $productid = Yii::$app->request->get("productid");
        $model = Product::find()->where('productid = :id', [':id' => $productid])->one();

        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();

            //上传封面图片和多张商品图片
            $uploadImgUrl = $this->upload($model, 'mod');
            $post['Product']['cover'] = $uploadImgUrl['cover'];
            $post['Product']['pics'] = $uploadImgUrl['pics'];

            //定义必要的属性值满足数据库字段类型限制
            $post['Product']['saleprice'] = ($post['Product']['saleprice'] != '') ? $post['Product']['saleprice'] : 0.00;
            $post['Product']['num'] = ($post['Product']['num'] != '') ? $post['Product']['num'] : 0;

            if ($model->load($post) && $model->save()) {
                Yii::$app->session->setFlash('info', '修改成功');
            }

        }
        
        return $this->render('add', ['model' => $model, 'opts' => $list]);
    }

    //上传封面图片和多张商品图片 $type为操作场景 'add'为添加商品 'mod'为编辑商品
    private function upload($model, $type)
    {
        $uploadImgUrl = [];

         //上传封面图片
        $file = UploadedFile::getInstance($model, "cover");
        if ($file)
        {
            $fileName = date("HiiHsHis").$file->baseName.".".$file->extension;
            $dir = "assets/upload/".$fileName;
            $file->saveAs($dir);

            $coverUrl = $dir;

            if ($type == 'mod') {
                unlink($model->cover);
            }
        }
        else
        {
            $coverUrl = ($type == 'add') ? '' : $model->cover;
        }

        //上传多张商品图片
        $picsArray = [];
        $pics = UploadedFile::getInstances($model, "pics");
        if ($pics)
        {
            $num = 0;
            foreach ($pics as $pic)
            {
                $key = uniqid();
                $num ++; //避免文件名重复(循环中uniqid()可能重复)
                $fileName = $key.$num.date("HiiHsHis").$pic->baseName.".".$pic->extension;
                $dir = "assets/upload/".$fileName;
                $pic->saveAs($dir);

                $arrayKey = $num.$key; //避免数组索引重复造成写入数据库出错
                $picsArray[$arrayKey]= $dir;
            }

            $picsUrl = implode(' ', $picsArray);

            if ($type == 'mod') {
                foreach(explode(' ', $model->pics) as $picurl) {
                    unlink($picurl);
                }
            }
        }
        else
        {
            $picsUrl = ($type == 'add') ? '' : $model->pics;
        }

        $uploadImgUrl['cover'] = $coverUrl;
        $uploadImgUrl['pics'] = $picsUrl;

        return $uploadImgUrl;
    }

    public function actionRemovepic()
    {
        $key = Yii::$app->request->get("key");
        $productid = Yii::$app->request->get("productid");
        $model = Product::find()->where('productid = :pid', [':pid' => $productid])->one();
        $qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
        $qiniu->delete($key);
        $pics = json_decode($model->pics, true);
        unset($pics[$key]);
        Product::updateAll(['pics' => json_encode($pics)], 'productid = :pid', [':pid' => $productid]);
        return $this->redirect(['product/mod', 'productid' => $productid]);
    }

    public function actionDel()
    {
        $productid = Yii::$app->request->get("productid");
        $model = Product::find()->where('productid = :pid', [':pid' => $productid])->one();
        $key = basename($model->cover);
        $qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
        $qiniu->delete($key);
        $pics = json_decode($model->pics, true);
        foreach($pics as $key=>$file) {
            $qiniu->delete($key);
        }
        Product::deleteAll('productid = :pid', [':pid' => $productid]);
        return $this->redirect(['product/list']);
    }

    public function actionOn()
    {
        $productid = Yii::$app->request->get("productid");
        Product::updateAll(['ison' => '1'], 'productid = :pid', [':pid' => $productid]);
        return $this->redirect(['product/list']);
    }

    public function actionOff()
    {
        $productid = Yii::$app->request->get("productid");
        Product::updateAll(['ison' => '0'], 'productid = :pid', [':pid' => $productid]);
        return $this->redirect(['product/list']);
    }









}
